//处理逻辑层

const userLibrary = require('../db/userLibrary')
const { createUserJwtToken, verifyJwtToken, encodedInput } = require('../util/server_jwt');

//查询用户是否存在
 //通过用户唯一标识open_id查询用户是否存在
async function checkUserExistByOpenid(openid) {
    let result = await userLibrary.checkUserExistByOpenid({openid: openid});

    //result内的result有三种{0,1,2}   0表示查询数据库记录时异常，1表示用户存在，2表示用户不存在   
    //不会返回0的状态   会在前面函数直接catch

    switch (result.success) {
        case 1: // 用户存在
            return {result: true, uid: result.uid};
        case 2: // 用户不存在
            return {result: false};
        default: // 0表示查询数据库记录时异常
            throw new Error('查询数据库记录时异常');
    }
};

//检测用户登录
async function checkWxUserLogin(data) {
    let openid = data;
    let result = await verifyJwtToken(openid);

    return result;
}



//添加用户
async function addUser(user) {
    let result = await userLibrary.addUser(user);
    if (result.result) {
        return true;
    }
    return false;
}



//-----------------------------------------------------------------------------------------------------
//web端 

//web端用户注册
async function createNewUser(userInfo) {
    if(userInfo && userInfo.email && userInfo.account && userInfo.password){
        let result = await userLibrary.createNewUser(userInfo);
        return result;
    }else{
      return {success:false};
    }
}


//web端用户登录
async function userLogin(userLoginInfo) {
    if(userLoginInfo && userLoginInfo.account && userLoginInfo.password){
        let result = await userLibrary.userLogin(userLoginInfo);
        return result;
    }
    return {success: false, msg: "账号或密码未输入"};
}

//web端修改管理员个人信息
async function updateUserInfo(userinfo) {
    let result = await userLibrary.updateAdminUserInfoById(userinfo);
    if (result.success) {
        return result;
    }
    return {success:false};
}


//管理员新建活动
async function createNewActivity(newActivity){
    let result = await userLibrary.createNewActivity(newActivity);
        return result;

    return {success:false};
}

//活动列表----查看所有活动
async function getAllActivities(){
        let result = await userLibrary.getAllActivities();

        if (result.success)
         return result;
   
        return {success:false};
    }

//活动列表页面查看某活动细节
async function activityDetails(activityName){
        let result = await userLibrary.activityDetails(activityName);

        if (result.success) 
        return result;

        return {success:false};
    }

//增加商品
async function addGoods(goodsInfo){
        let result = await userLibrary.addGoods(goodsInfo);
        return result;
        
        // if (result.success) 
            return {success:false};
}

 
module.exports = {checkWxUserLogin, updateUserInfo, checkUserExistByOpenid, createNewActivity, addUser, createNewUser, userLogin, getAllActivities, activityDetails, addGoods};